package com.yalu.read.excel.sale;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.yalu.entity.SaleData;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class SaleTenTwoExcelRead {

    /**
     * 测试pdf文件的创建
     *
     * @param args
     */
    public static void main(String[] args) {
        String filePath = "D://yalu//sale//";  //这里先手动把绝对路径的文件夹给补上。
        List<String> filePaths = new ArrayList<>();
        recursionFile(filePath, filePaths);
        List<SaleData> list = new ArrayList<>();
        for (String fileName : filePaths) {
            readExcel(fileName, list);
        }
        System.out.println("文件数量：" + filePaths.size() + " 数据数量: " + list.size());
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String outFileName = "D:\\yalu\\销售单_" + LocalDateTime.now().format(dtf) + ".xlsx";
        writerFils(list, outFileName);
    }

    /**
     * 读PDF文件，使用了pdfbox开源项目
     *
     * @param fileName
     */
    public static void readExcel(String fileName, List<SaleData> list) {
        File file = new File(fileName);
        FileInputStream in = null;
        InputStream inputStream;
        try {
            inputStream = new FileInputStream(fileName);
            boolean isOk = true;
            EasyExcel.readSheet(0);
            List<Object> dataList = EasyExcel.read(inputStream).headRowNumber(0).doReadAllSync();
            int size = dataList.size();
            Queue<SaleData> dataQueue = new LinkedList<>();
            boolean isEnd = false;
            for (int i = 0; i < size; i++) {
                SaleData dataNow = dataQueue.poll();
                SaleData saleData = new SaleData();
                if (null != dataNow) {
                    BeanUtils.copyProperties(dataNow, saleData);
                }
                LinkedHashMap linkedHashMap = (LinkedHashMap) dataList.get(i);
                String lineText = JSON.toJSONString(linkedHashMap);
                if (StringUtils.hasText(lineText) && lineText.contains("形式发票编号")) {
                    int mapSize = linkedHashMap.size();
                    boolean isFirst = false;
                    boolean isTwo = false;
                    String one = null;
                    String two = null;
                    for (int j = 0; j < mapSize; j++) {
                        String content = String.valueOf(linkedHashMap.get(j)).trim();
                        if (StringUtils.hasText(content) && !"null".equals(content)) {
                            if (content.contains("形式发票编号")) {
                                isFirst = true;
                            } else if (isFirst) {
                                one = content;
                                isFirst = false;
                            } else if (content.contains("订货日期")) {
                                isTwo = true;
                            } else if (isTwo) {
                                two = content;
                                break;
                            }
                        }
                    }
                    if (StringUtils.hasText(one) && StringUtils.hasText(two)) {
                        saleData.setSaleNo(one);
                        saleData.setDate(two);
                    }
                    if (StringUtils.hasText(one)) {
                        saleData.setSaleNo(one);
                    }
                } else if (StringUtils.hasText(lineText) && lineText.contains("订货单位")) {
                    int mapSize = linkedHashMap.size();
                    boolean isFirst = false;
                    for (int j = 0; j < mapSize; j++) {
                        String content = String.valueOf(linkedHashMap.get(j)).trim();
                        if (StringUtils.hasText(content) && !"null".equals(content)) {
                            if (StringUtils.hasText(content) && content.contains("订货单位")) {
                                isFirst = true;
                            } else if (isFirst) {
                                saleData.setName(content);
                                break;
                            }
                        }
                    }
                } else if (StringUtils.hasText(lineText) && lineText.contains("Total Amount")) {
                    int mapSize = linkedHashMap.size();
                    for (int j = 0; j < mapSize; j++) {
                        String content = String.valueOf(linkedHashMap.get(j));
                        if (content.contains("Total Amount")) {
                            String[] totalAmounts = content.split("Total Amount");
                            saleData.setCurrency(totalAmounts[1].replace("(", "").replace(")", "").trim());
                        }
                    }
                } else if (StringUtils.hasText(lineText) && (lineText.contains("合计(Total)"))) {
                    int mapSize = linkedHashMap.size();
                    boolean isFirst = false;
                    String one = null;
                    String two = null;
                    for (int j = 0; j < mapSize; j++) {
                        String content = String.valueOf(linkedHashMap.get(j)).trim();
                        if (StringUtils.hasText(content) && !"null".equals(content)) {
                            if (StringUtils.hasText(content) && content.contains("合计(Total)")) {
                                continue;
                            } else if (!isFirst) {
                                one = content;
                                isFirst = true;
                            } else {
                                two = content;
                                break;
                            }
                        }
                    }
                    if (StringUtils.hasText(one) && StringUtils.hasText(two)) {
                        saleData.setTotal(one);
                        saleData.setAmount(two);
                    } else if (StringUtils.hasText(one)) {
                        saleData.setAmount(one);
                    }
                    isEnd = true;
                }
                dataQueue.offer(saleData);
                if (isEnd) {
                    SaleData data = dataQueue.poll();
                    data.setFileName(fileName);
                    list.add(data);
                    isOk = false;
                    isEnd = false;
                    continue;
                }
            }
            if (isOk) {
                System.out.printf("未处理文件:" + fileName);
                SaleData saleData = new SaleData();
                saleData.setFileName(fileName);
                list.add(saleData);
            }
        } catch (Exception e) {
            System.out.println("读取PDF文件" + file.getAbsolutePath() + "生失败！" + e);
            e.printStackTrace();
            SaleData saleData = new SaleData();
            saleData.setFileName(fileName);
            list.add(saleData);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    private static boolean isNull(String str) {
        boolean isNull = false;
        if (StringUtils.hasText(str)) {
            if (!"null".equals(str) && !"[null".equals(str) && !"null]".equals(str)) {
                isNull = true;
            }
        }
        return isNull;
    }

    /**
     * 写入文件
     *
     * @param data
     * @param outFileName
     */
    public static void writerFils(List<SaleData> data, String outFileName) {
        try {
            ExcelWriter excelWriter = EasyExcel.write(outFileName, SaleData.class).build();
            String sheetName = "1";
            WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
            excelWriter.write(data, writeSheet);
            // 千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
        } catch (Exception e) {
            System.out.println("文件写入失败：" + e.getMessage());
        }
    }

    /**
     * 递归文件
     *
     * @param path
     * @param filePaths
     */
    public static void recursionFile(String path, List<String> filePaths) {
        if (StringUtils.hasText(path)) {
            File file = new File(path);
            for (File f : file.listFiles()) {
                if (f.isDirectory()) {
                    recursionFile(f.getPath(), filePaths);
                } else {
                    if (f.getPath().toLowerCase().contains(".xls") || f.getPath().toLowerCase().contains(".xlsx")) {
                        filePaths.add(f.getPath());
                    }
                }
            }
        }
    }
}
